<!-- 工作台-我的任务-我的待办 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <px-button style="margin-top: 24px; margin-bottom: -8px" icon="ArrowLeft" type="primary" @click="backMainPage">返回 </px-button>
      <CustomTabs class="mt-[14px]" :timer="updateKey" :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px" style="padding-top: 14px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="名称">
              <px-input
                v-model="queryParams.taskTitle"
                placeholder="请输入名称"
                maxlength="50"
                clearable
                @blur="queryParams.taskTitle = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="计划完成时间" prop="startTimeRange">
              <px-date-picker
                v-model="queryParams.startTimeRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 368px)" border>
        <px-table-column label="序号" width="50" align="center" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </px-table-column>
        <px-table-column prop="taskTitle" label="名称" min-width="200" show-overflow-tooltip />
        <px-table-column label="任务来源" prop="taskResource">
          <template #default="scope">
            {{ scope.row["taskResource"] || "-" }}
          </template>
        </px-table-column>
        <px-table-column label="任务状态" prop="taskProgress">
          <template #default="scope">
            {{ scope.row["taskProgress"] || "-" }}
          </template>
        </px-table-column>
        <px-table-column label="计划完成时间" prop="taskFinishTime" width="160">
          <template #default="scope">
            {{ scope.row["taskFinishTime"] || "-" }}
          </template>
        </px-table-column>
        <px-table-column align="center" label="操作" width="100">
          <template #default="scope">
            <px-button v-has="'ALL_BENCH_TASK_HANDLE_VIEW'" link type="primary" @click="handleDetail(scope.row)">详情</px-button>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
      <ScheduleDetail v-model:dialogVisible="scheduleDetailVisible" :data="scheduleDetailData" @refresh="initData" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getTaskList, queryTaskList } from "@/api/bench";
import CustomTabs from "@/components/Tabs/index.vue";
import { getToken } from "@/utils/auth";
import { stringTrimOfParams } from "@/utils/common";
import { PxMessage } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import ScheduleDetail from "../../task/canlendar/components/ScheduleDetail/index.vue";

const router = useRouter();
const route = useRoute();
const state = reactive<any>({
  tabList: [],
  activeName: "UNDO",
  queryParams: {
    taskTitle: "",
    taskType: "HANDLE",
    taskStatus: "UNDO",
    pageNum: 1,
    pageSize: 20,
    startTimeRange: []
  },
  taskTableData: {
    undoNumber: "-",
    doneNumber: "-"
  },
  tableData: [],
  total: 0,
  updateKey: ""
});
const { tabList, updateKey, activeName, queryParams, taskTableData, tableData, total } = toRefs(state);

const initData = async () => {
  taskTableData.value = await getTaskList();
  tabList.value = [
    {
      name: "UNDO",
      label: `我的待办（${taskTableData.value?.undoNumber}）`
    },
    {
      name: "DONE",
      label: `我的已办（${taskTableData.value?.doneNumber}）`
    }
  ];
  if (route?.query && route?.query?.type) {
    const { type, startTime, endTime } = route?.query;
    activeName.value = type;
    queryParams.value.taskStatus = type;
    queryParams.value.startTimeRange = [startTime, endTime];
  }
  queryTable();
  updateKey.value = new Date().getTime();
};
// 进入页面时触发
onMounted(() => {
  initData();
});
const backMainPage = () => {
  router.push("/all/bench/home");
};
// 获取开始日期及结束日期
const changeDate = val => {
  if (val && val.length > 0) {
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = "";
    queryParams.value.endTime = "";
  }
};
// 查询列表
const queryTable = async () => {
  const { startTimeRange, ...others } = queryParams.value;
  const startTime = startTimeRange && startTimeRange[0] ? `${startTimeRange[0]} 00:00:00` : undefined;
  const endTime = startTimeRange && startTimeRange[0] ? `${startTimeRange[1]} 23:59:59` : undefined;
  const data: any = await queryTaskList(stringTrimOfParams({ ...others, startTime, endTime }));
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和列表
const resetTable = async () => {
  queryParams.value = {
    taskTitle: "",
    taskType: "HANDLE",
    taskStatus: queryParams.value.taskStatus,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    startTimeRange: []
  };
  queryTable();
};
// 切换tabs调用接口
const handelTabSelected = selectName => {
  activeName.value = selectName;
  if (selectName === "UNDO") {
    queryParams.value.taskStatus = "UNDO";
  } else if (selectName === "DONE") {
    queryParams.value.taskStatus = "DONE";
  }
  queryTable();
};
const scheduleDetailVisible = ref(false);
const scheduleDetailData = ref();
// 打开详情
const handleDetail = data => {
  if (data.taskResource === "我的日程") {
    // 1、手动添加日程
    scheduleDetailVisible.value = true;
    scheduleDetailData.value = data;
  } else {
    // 2、任务流转日程
    if (data?.taskResourceUrl) {
      // 设备保养因为是iframe嵌套模式，消息跳转时需要带上当前登录人的token
      if (data.taskModuleName === "PMS") {
        const token = getToken().accessToken || "";
        if (/^http/.test(data.taskResourceUrl)) {
          window.open(`${data.taskResourceUrl}&ssoToken=${token}`);
        } else {
          router.push(`${data.taskResourceUrl}&ssoToken=${token}`);
        }
      } else {
        if (/^http/.test(data.taskResourceUrl)) {
          window.open(data.taskResourceUrl);
        } else {
          router.push(data.taskResourceUrl);
        }
      }
    } else {
      PxMessage.error("请配置正确的跳转地址");
    }
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
</style>
